package cqrtplm.aop;

import com.alibaba.fastjson.JSONObject;
import com.hustcad.plm.basic.util.TyplmLoggerUtil;
import com.hustcad.plm.pdm.classification.mapper.TyplmClassificationMapper;
import com.hustcad.plm.pdm.classification.model.constant.TyplmClassificationErrorCodeEnum;
import com.hustcad.plm.pdm.classification.service.impl.TyplmClassificationServiceImpl;
import com.hustcad.plm.pdm.common.util.CommonUtil;
import com.ty.basic.entity.CTyEntityBaseDO;
import com.ty.basic.entity.IdentifierEntity;
import com.ty.basic.entity.type.ClassificationDO;
import com.ty.basic.utils.BatchQueryHelper;
import cqrtplm.constant.RTErrorCodeEnum;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import com.ty.basic.handler.exceptionhandler.response.ResponseResult;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Aspect
@Component
@Slf4j
public class ClassCodeModifyAOP {
    @Resource
    private TyplmClassificationServiceImpl typlmClassificationService;
    @Resource
    private TyplmClassificationMapper typlmClassificationMapper;

    @Around("execution(* com.hustcad.plm.pdm.code.controller.TyplmCodeController.saveClassificationCode(..))")
    @SneakyThrows
    public Object aroundSaveClassificationCode(ProceedingJoinPoint joinPoint) {
        // 获取方法参数
        Object[] args = joinPoint.getArgs();

        // 提取 JSONObject 参数
        if (args.length > 0 && args[0] instanceof JSONObject) {
            JSONObject reqJson = (JSONObject) args[0];

            // 从info对象中获取baseoid和lastcode
            JSONObject info = reqJson.getJSONObject("info");
            if (info != null) {
                String baseoid = info.getString("baseoid");
                log.info("获取到baseoid的值: {}", baseoid);

                // 检查是否存在lastcode字段
                if (info.containsKey("lastcode")) {
                    String lastcode = info.getString("lastcode");
                    log.info("获取到lastcode的值: {}", lastcode);

                    // 在这里添加你的判断逻辑
                    // 例如：如果lastcode不为空且满足某些条件，则阻止执行
                    if (lastcode != null && !lastcode.isEmpty()) {
                        try {
                            // 获取分类信息
                            ClassificationDO classificationDO = (ClassificationDO) this.typlmClassificationMapper.selectByPrimaryKey(
                                    new BigInteger(baseoid));
                            if (classificationDO != null) {
                                // 只检查当前分类，不包括子分类
                                BigInteger currentId = new BigInteger(baseoid);
                                List<BigInteger> currentOnly = Arrays.asList(currentId);
                                // 调用检查逻辑，如果有对象使用该分类会抛出异常
                                checkClassificationUsed(currentOnly, classificationDO);
                            }
                        } catch (Exception e) {
                            throw  RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException("该分类已经存在实例化对象，无法修改分类码");
                        }

                        // 添加你的业务判断逻辑
                        // 如果不符合条件，返回错误信息
                        // return ResponseResult.fail("lastcode已存在，不允许修改");
                    }
                }
                // 如果没有lastcode字段，则正常执行程序（不做任何处理）
            }

            // 记录完整的请求参数
            log.info("拦截到 saveClassificationCode 请求参数: {}", reqJson);
        }

        // 继续执行原方法
        return joinPoint.proceed();
    }


    // 在需要的地方调用
    private void checkClassificationUsed(List<BigInteger> ids, ClassificationDO classificationDO) {
        TyplmLoggerUtil.debug(log, () -> {
            return "检查分类是否被对象使用的入参ids==>【{}】";
        }, () -> {
            return new Object[]{ids};
        });

        List<IdentifierEntity> identifierEntities = BatchQueryHelper.batchSplitQuery(
                ids, typlmClassificationMapper::checkClassificationListIsUsed);

        if (!CollectionUtils.isEmpty(identifierEntities)) {
            TyplmLoggerUtil.debug(log, () -> {
                return "检查分类是否被对象使用的identifierEntities==>【{}】";
            }, () -> {
                return new Object[]{JSONObject.toJSONString(identifierEntities)};
            });

            List<CTyEntityBaseDO> usedEntityList = CommonUtil.getEntityListIgnoreNotExist(identifierEntities);
            if (!CollectionUtils.isEmpty(usedEntityList)) {
                List<CTyEntityBaseDO> usedSetEntityList = new ArrayList<>(usedEntityList);
                if (usedSetEntityList.size() > 3) {
                    for (int i = usedSetEntityList.size() - 1; i >= 2; --i) {
                        usedSetEntityList.remove(i);
                    }
                }

                String displayName = CommonUtil.getEntityDisplayName(usedSetEntityList);
                if (ids.size() > 1) {
                    if (usedEntityList.size() > 3) {
                        throw TyplmClassificationErrorCodeEnum.CLASSFICATION_OBJECT_ASCHILD_MANY_DELETE_FAILURE.getException(
                                new Object[]{classificationDO.getName(), displayName});
                    } else {
                        throw TyplmClassificationErrorCodeEnum.CLASSFICATION_OBJECT_ASCHILD_DELETE_FAILURE.getException(
                                new Object[]{classificationDO.getName(), displayName});
                    }
                } else if (usedEntityList.size() > 3) {
                    throw TyplmClassificationErrorCodeEnum.CLASSFICATION_OBJECT_MANY_DELETE_FAILURE.getException(
                            new Object[]{classificationDO.getName(), displayName});
                } else {
                    throw TyplmClassificationErrorCodeEnum.CLASSFICATION_OBJECT_DELETE_FAILURE.getException(
                            new Object[]{classificationDO.getName(), displayName});
                }
            }
        }
    }
}